<?php
require_once 'pages/TMSFrontContentPage.inc';

class TMSFrontProductPage extends TMSFrontContentPage {
/**
 * @var TCMSCommentModel
 */	
	protected $_ioc_comments_model_;
	
/**
 * 
 * @var TMSProductSitePublisher
 */	
	
	protected $_ioc_publisher_;
	
	protected $_int_comments_count_;
	
	private $_comm_page_;
	
	private $_comm_total_count_ = 0;
	
	public function Handle(THttpRequest $request){
		if (isset($request->pn))
			$this->_comm_page_ = $request->pn;

		if (isset($request->id) || isset($request->slug))
			return parent::Handle($request);
			
		if ($this->pageItem)
			return TMSFrontPage::Handle($request);
		return false;
	}
	
	public function __get($nm){
		switch ($nm){
			case 'CurrentListPage':return $this->_comm_page_;break;
			case 'CommentPagesCount':return ceil($this->_comm_total_count_/$this->_int_comments_count_);break;
			default:return parent::__get($nm);break;
		}
	}

	public function Path(){
		$category = null;
		foreach ($this->pageItem->Categories as $c){
			$category = $this->CategoriesModel->WrapObject($c);
			break;
		}
		$result = array();
		if ($category){
			$result[] = new TMSFrontPageItem($category,$this);
			$p = $category->Container();
			while ($p && ($p->Slug != $this->service->CatalogRoot)){
				$result[] = new TMSFrontPageItem($p,$this);
				$p = $p->Container();
			}
		}
		else
			$this->getNestedPagePath($this->pageItem, $result);
		return array_reverse($result);
	}
		
	public function BuyUrl(){
		return $this->Url(null,'Buy',array('product'=>$this->pageItem->Product->Id));
	}
	
	public function http_AddComment($author,$comment,$captcha){
		if (!$this->User){
			$this->checkCaptcha($captcha);
			if (!$author){
				throw new TExposableException('Необходимо указать автора комментария!');
				die;
			}
		}
		$this->CommentsModel->CreateItem(array('Page'=>$this->pageItem->Id,'NickName'=>$author,'CommentText'=>$comment));
	}
	
	public function ListPageUrl($page){
		return $this->Url(null,null,array('pn'=>$page));
	}
	
	public function Product(){
		return $this->pageItem->Product;
	}
	
	public function Images(){
		return $this->Product()->Images;
	}
	
	public function Comments(){
		$lo = new TListOptions(array(
				new TFilterOption('Page', TConditionType::C_EQUAL, $this->pageItem->Id),
				new TFilterOption('IsApproved', TConditionType::C_EQUAL, true)
				), array(new TSortingOption('Added',TSortingType::SORT_DESC)));
		if ($this->_int_comments_count_){
			$lo->Offset = $this->_comm_page_?($this->_comm_page_ - 1)*$this->_int_comments_count_:0;  
			$lo->Count = $this->_int_comments_count_;
		}
		return $this->CommentsModel->GetList($lo,$this->_comm_total_count_);
	}
	
	protected function processUrlParameters(array $parameters){
		$parameters = parent::processUrlParameters($parameters);
		if (!isset($parameters['pn']))
			$parameters['pn'] = $this->_comm_page_;
		return $parameters;
	}	
}
